package com.senseuni.da.utils;

import android.util.Base64;

import com.elvishew.xlog.XLog;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密工具类
 *
 */
public class AESUtils {
    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 算法定义
     */
    private static final String AES_ALGORITHM = "AES";
    /**
     * 指定填充方式
     */
    private static final String CIPHER_PADDING = "AES/ECB/PKCS5Padding";
    private static final String CIPHER_CBC_PADDING = "AES/CBC/PKCS5Padding";
    /**
     * 偏移量(CBC中使用，增强加密算法强度)
     */
    private static final String IV_SEED = "1234567812345678";

    /**
     * AES加密
     * @param content 待加密内容
     * @param aesKey  密码
     * @return
     */
    public static String encrypt(String content, String aesKey){
        if(StringUtils.isBlank(content)){
            XLog.e("AES encrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if(StringUtils.isNotBlank(aesKey) && aesKey.length() == 16){
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(ENCODING);
                //设置加密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
                //选择加密
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                //根据待加密内容生成字节数组
                byte[] encrypted = cipher.doFinal(content.getBytes(ENCODING));
                //返回base64字符串
                return Base64.encodeToString(encrypted, Base64.DEFAULT);
            } catch (Exception e) {
                XLog.e("AES encrypt exception:" + e.getMessage());
                throw new RuntimeException(e);
            }

        }else {
            XLog.e("AES encrypt: the aesKey is null or error!");
            return null;
        }
    }

    /**
     * 解密
     *
     * @param content 待解密内容
     * @param aesKey  密码
     * @return
     */
    public static String decrypt(String content, String aesKey){
        if(StringUtils.isBlank(content)){
            XLog.e("AES decrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if(StringUtils.isNotBlank(aesKey) && aesKey.length() == 16){
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(ENCODING);
                //设置解密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
                //选择解密
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);

                //先进行Base64解码
                byte[] decodeBase64 = Base64.decode(content, Base64.DEFAULT);

                //根据待解密内容进行解密
                byte[] decrypted = cipher.doFinal(decodeBase64);
                //将字节数组转成字符串
                return new String(decrypted, ENCODING);
            } catch (Exception e) {
                XLog.e("AES decrypt exception:" + e.getMessage());
                throw new RuntimeException(e);
            }

        }else {
            XLog.e("AES decrypt: the aesKey is null or error!");
            return null;
        }
    }

    public static void main(String[] args) {
        // AES支持三种长度的密钥：128位、192位、256位。
        // 代码中这种就是128位的加密密钥，16字节 * 8位/字节 = 128位。
        String random = RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz1234567890");
        System.out.println("随机key:" + random);
        System.out.println();

        System.out.println("---------加密---------");
        String aesResult = encrypt("iVBORw0KGgoAAAANSUhEUgAAAFAAAABUCAYAAAAVgLC7AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAABK+SURBVHhe7ZwJeFXVtcf/uTe5GW7mkTAkwRAggWArmMTIJMr3MQgqPgq0FEFAKKh9SK1W/V59Uqm16muVig+rFZUWfDzRh1ooUJEvgIgoIIEwRiBAyEhububprbX3OclNOOfeczIwNX/d2cOZf3etPZ198GoioVvtlkWJu9VOdQPsoLoBdlDdADuoDgPkFqimoQm1FP4V1a5W+IijDn/Pr8G+0jrkVtSjulGWB1q90C/QioxwG8bF+iEuwCo33MAyBfBQWR1ePubEXgLnSWzaIyNtmJ0QgKEE1EsW33AyBLCR9njzVAVWUqg3ba9NGBzsjQcT7Lgzxg9kpDeUPALkjc8fLsfavCpZYEpN4nhxCf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JDEsIxj7oktwww3tJfSekC5GW1vDJUW9zvYoJyhUDzGJWCajGuEBmI2mhI95VgVXcWFqrsIyBSPrlnMObTYD8jObrTRw+dKV2Ap2g0Mll3NCKcV0Djw1VL5MpewCQo3FoyHOmy0ppUN2WwqjuLqSeKZR3YiH5RAZg35iaMHHRtg1OlC5A1/csSHHLotcSXu7Lo2BJEGRMchqgAZDgCopKX1ifrQk4nRvjjweFxGJ0SaWpZyNWWW4DbC2rwsNtpLbY+xQr52wFOsysTII5Fw0FBBSi7LNLSVOtLDvfDvPSeGJUU7nYFwLUqtwBZSwngZgKpLQmPz8AAhUszQBdLFNamABSuTAC5rrs5wg8P3RKDkX1DrwtX1ZNHgLzWmfuE+v+GjJsGRXVlJTDA9Cg/zB8SibRegeoM1HUtjwBZvOL+MbLEry9pdawJFP9lYHSqyxoUCj60bVysP+YMDEWqh5VR15sMAWTxy6O3cyvFkrXLJ1ElPD6Ta4NiJxOb0jsAD/QLRlzg1RmrdrUMA1TFH9Csz6vCpvxqnKpsYE9VJF3ZSvkBgVZM6umH+/rYEWxijcz1KNMAXcXfZ3xPEPkjam4Iwm0WJNitNzw0V3UIYLd0Xip1y7i6AXZQ3QA7qG6AHRLw/ypnAOsjf/pbAAAAAElFTkSuQmCC", "314xtkc6796r8w0c");
        System.out.println("aes加密结果:" + aesResult);
        System.out.println();

        System.out.println("---------解密---------");
        String decrypt = decrypt(aesResult, random);
        System.out.println("aes解密结果:" + decrypt);
        System.out.println();

    }
}